#-*- coding: UTF-8 -*-
#coding=UTF-8
from google.appengine.api import urlfetch
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api.memcache import Client
import os
import time
import datetime
import logging
class MainPage(webapp.RequestHandler):
    def get(self):
        dataString = datetime.date.today().strftime( "%y%m%d")
        mc = Client()
        data = mc.get(dataString)
        if data is None:
            data = self.qurey_data()
            mc.add(key=dataString, value=data, time=3600*25)
            
        '''赋值'''
        template_values = {
          'greetings': time.strftime("%Y-%m-%d"),
          'tuanQQInfo':data
          }
          
        path = os.path.join(os.path.dirname(__file__), 'index.html')
        self.response.out.write(template.render(path, template_values))

    
    ''''抓取QQ商城团的js数据.拼装展现'''
    def qurey_data(self):
        for i in range(0, 3):
            try:
                url = "http://tuan.qq.com/"
                result = urlfetch.fetch(url)
                if result.status_code == 200:
                    contents = result.content
                    begin = contents.find('<div class="mainbar tody_buy_group">');
                    end =  contents.find('<div class="detail_today_buy">');
                    return contents[begin:end]
                else:
                    continue
            except urlfetch.Error:
                logging.error('urlfetch.Error http://tuan.qq.com/ Marked!try again')
                continue


application = webapp.WSGIApplication(
                                     [('/', MainPage)],
                                     debug=True)
def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
